package com.fadis.protocol;

import com.fadis.FadisException;
import com.fadis.data.base.FadisString;

import java.io.UnsupportedEncodingException;

public class BulkString extends BaseRespProtocol {

    private String str;

    public BulkString() {
        this.str = null;
    }


    public BulkString(String str) {
        this.str = str;
    }

    public BulkString(FadisString str) {
        this.str = (str == null ? null : str.getStr());
    }

    public String getStr() {
        return str;
    }

    @Override
    public String encode() {
        if(str == null){
            return "$-1\r\n";
        }else if(str.equals("")){
            return "$0\r\n\r\n";
        }else{
            try {
                String ss = "${len}\r\n{s}\r\n";
                byte[] bytes = str.getBytes("utf-8");
                int len = bytes.length;
                ss = ss.replace("{len}", len + "");
                ss = ss.replace("{s}", str);
                return ss;

            } catch (UnsupportedEncodingException e) {
                throw new FadisException(1008, e.getMessage());
            }
        }
    }

    public static String encodedNull(){
        return CmdEncoder.getDefault().encode(new BulkString());
    }

    public static String encodedBulkString(String s){
        return CmdEncoder.getDefault().encode(new BulkString(s));
    }

    public static String encodedBulkString(FadisString s){
        return CmdEncoder.getDefault().encode(new BulkString(s));
    }

}
